//
//  ReadingFileController.m
//  LuCaiZhu
//
//  Created by Stella on 2018/9/25.
//
#import "Header.h"
#import "UIColor+NN.h"
#import "VerifySMSController.h"
#import "TopFileHeaderCell.h"
#import "CKPuslichTool.h"
#import "SVProgressHUD.h"
#import "LoopProgressView.h"
#import <WebKit/WebKit.h>
#import "HandleNetProduct.h"
#import "HWCircleView.h"

#import "ReadingFileController.h"

#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

@interface ReadingFileController ()<UIWebViewDelegate,UIScrollViewDelegate,WKNavigationDelegate,WKUIDelegate>{
    NSInteger totalPage;//PDF文件总页数
    float totalHeight;//PDF文件总高度
    int currentPage;
    
    
    int readerTime;
    
    NSString *bookingId;
    NSString *stepName;
    
    NSString *personlEmail;
}
@property (weak, nonatomic) IBOutlet UIWebView *mWebView;
@property (weak, nonatomic) IBOutlet UIButton *iAgreeButton;
@property (nonatomic, copy) NSString *fileName;
@property (nonatomic, copy) NSString *filePath;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *webViewBottom;

@property (weak, nonatomic) IBOutlet UILabel *timeLa;
@property (strong, nonatomic) NSTimer *runTimer;//30秒倒计时
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *webTopHeight;
@property (weak, nonatomic) IBOutlet UIView *topView;

@property (weak, nonatomic) IBOutlet UICollectionView *mCollection;
@property (strong, nonatomic)NSArray *topHeaders;
@property (strong, nonatomic)NSArray *topTitles;
@property (weak, nonatomic) IBOutlet UIView *downView;

//wkwebView
@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) WKWebViewConfiguration *wkConfig;


@property (nonatomic, weak) HWCircleView *circleView;
@property (strong, nonatomic) NSTimer *proTimer;
@end

@implementation ReadingFileController

#pragma mark - 初始化wkWebView

//- (WKWebViewConfiguration *)wkConfig {
//    if (!_wkConfig) {
//        _wkConfig = [[WKWebViewConfiguration alloc] init];
//        _wkConfig.allowsInlineMediaPlayback = YES;
//        _wkConfig.allowsPictureInPictureMediaPlayback = YES;
//
//    }
//    return _wkConfig;
//}
//
//- (WKWebView *)wkWebView {
//    if (!_wkWebView) {
//        _wkWebView = [[WKWebView alloc] initWithFrame:_mWebView.frame configuration:self.wkConfig];
//        _wkWebView.navigationDelegate = self;
//        _wkWebView.UIDelegate = self;
//        [_wkWebView.scrollView setOpaque:NO];
//        _wkWebView.scrollView.backgroundColor = [UIColor whiteColor];
//        _wkWebView.scrollView.delegate = self;
//        [_wkWebView setOpaque:NO];
//
//        _wkWebView.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
//        [self.view insertSubview:_wkWebView atIndex:0];
//    }
//    return _wkWebView;
//}

//- (void)dealloc{
//    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    readerTime = 30;
    personlEmail = @"";
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    self.iAgreeButton.enabled = NO;
    self.timeLa.backgroundColor = [UIColor colorWithHexString:@"bfbfbf"];

    NSLog(@"self.stepDic---%@",self.stepDic);
    bookingId = _stepDic[@"BookingId"];
    stepName = _stepDic[@"StepName"];
    self.title = _stepDic[@"StepName2"];
    if ([self.title isEqualToString:@"基金合同"]) {
        //如果是基金合同，需要PDF定位
        self.webTopHeight.constant = 64;
        self.topView.hidden = NO;
        
        //PDF定位，获取总页数
        [self getHetongDatas];
    }else{
        self.webTopHeight.constant = 0;
        self.topView.hidden = YES;
        [self getDatas];
    }
    
    self.mWebView.hidden = YES;
    //圆圈
//    HWCircleView *circleView = [[HWCircleView alloc] initWithFrame:CGRectMake(Main_Screen_Width/2-30, Main_Screen_Height/2-30, 60, 60)];
//    [self.view addSubview:circleView];
//    self.circleView = circleView;
//    [self initMyCircleProgress];
}

- (void)initMyCircleProgress{
    _circleView.hidden = NO;
    _proTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:_proTimer forMode:NSRunLoopCommonModes];
}

- (void)timerAction
{
    
    if (_circleView.progress >= 0.98) {
        return;
    }
    _circleView.progress += 0.02;
}


- (void)getHetongDatas{
    [HandleNetProduct getSignFundContractWithBookingID:bookingId Success:^(NSDictionary *data) {
        /**
         Element = "";要素
         FundContractURl = "";
         Page = "";页数
         Seq = "";序号
         **/
        NSString *pages = data[@"Page"];
        _topHeaders = [pages componentsSeparatedByString:@","];
        NSString *titles = data[@"Element"];
        _topTitles = [titles componentsSeparatedByString:@","];
//        NSLog(@"_topTitles -- %@ _topHeaders -- %@",_topTitles,_topHeaders);
        if (pages.length > 0 && titles.length >0) {
            
        }else{
            self.webTopHeight.constant = 0;
            self.topView.hidden = YES;
        }
        personlEmail = [NSString stringWithFormat:@"%@",data[@"PersonEmail"]];
        [self loadPDFFiles:data[@"FundContractURl"]];
    } Failure:^(NSString *errorInfo) {
        
    }];

}

- (void)getDatas{
    NSString *name;
    NSString *urlSt;
    NSLog(@"self.title---%@  bookingId -----%@",self.title,bookingId);
    //获取风险揭示书Risk基金业务申请表FundBusiness投资者匹配书Investor
    if ([self.title rangeOfString:@"风险揭示书"].length>0) {
        name = @"Risk";
        urlSt = @"RiskURl";
    }else if ([self.title rangeOfString:@"基金业务申请表"].length > 0){
        name = @"FundBusiness";
        urlSt = @"FundURl";
    }else if ([self.title rangeOfString:@"投资者匹配告知书"].length >0){
        name = @"Investor";
        urlSt = @"InvestorURl";
    }else if ([self.title rangeOfString:@"认购告知书"].length >0){
        name = @"SignBooking";
        urlSt = @"SignBookingURL";
    }else if ([self.title rangeOfString:@"份额确认书"].length >0){
        name = @"ShareConfirm";
        urlSt = @"ShareURL";
    }else{
        name = @"";
        urlSt = @"";
    }
    
    [HandleNetProduct getSignPDFWithMethoname:name BookingID:bookingId Success:^(NSDictionary *data) {
        if ([name isEqualToString:@"ShareConfirm"]) {
            personlEmail = [NSString stringWithFormat:@"%@",data[@"PersonEmail"]];
        }
        [self loadPDFFiles:data[urlSt]];
    } Failure:^(NSString *errorInfo) {
        
    }];
}

- (void)loadPDFFiles:(NSString *)urlString{
    NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
    NSString *encodeUrl = [urlString stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet];
    NSLog(@"encodeUrl---%@",encodeUrl);
    NSURL *url = [NSURL URLWithString:encodeUrl];
    CGPDFDocumentRef pdfDocument =[self pdfRefByDataByUrl:url];
    totalPage = CGPDFDocumentGetNumberOfPages(pdfDocument);
    NSLog(@"totalPage----%d",(int)totalPage);
    
    if (totalPage > 0) {
        currentPage = 0;
        [_mCollection reloadData];
    }
    
    [HandleNetProduct show];
    _mWebView.delegate = self;
    _mWebView.scrollView.delegate = self;
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.mWebView loadRequest:request];

    
//    [self.wkWebView loadRequest:request];
//    [self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}

//在监听方法中获取网页加载的进度，并将进度赋给progressView.progress

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
       float  progress = self.wkWebView.estimatedProgress;
       
        NSLog(@"progress----%f",progress);
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


- (void)loadMyTimer{
    if ([self.stepDic[@"Status"] isEqualToString:@"完成"] ) {

        if ([self.SigningStatus isEqualToString:@"B"]&& ([self.title isEqualToString:@"基金合同"] ||[self.title isEqualToString:@"份额确认书"] )) {
            self.downView.hidden = NO;
            self.webViewBottom.constant = 70;
            _timeLa.text = @"@下载至邮箱";
            self.iAgreeButton.enabled = YES;
            self.timeLa.backgroundColor = MAIN_COLOR_Red;
        }else{
            self.downView.hidden = YES;
            self.webViewBottom.constant = 10;
        }

    }else{
        self.downView.hidden = NO;
        self.webViewBottom.constant = 70;
        int time = [self.stepDic[@"Countdown"] intValue];
        
        if (time > 0) {
            self.timeLa.text = [NSString stringWithFormat:@"我已阅读，确认无误并同意签字（%ds）",time];
            readerTime = time;
            if (_runTimer!=nil) {
                [_runTimer invalidate];
            }
            [NSThread detachNewThreadSelector:@selector(bannerStart)toTarget:self withObject:nil];
        }else{
            self.iAgreeButton.enabled = YES;
            self.timeLa.backgroundColor = MAIN_COLOR_Red;
            _timeLa.text = @"我已阅读，确认无误并同意签字";
        }
        
    
    
    }
    if (totalPage == 0) {
        self.webTopHeight.constant = 0;
        self.topView.hidden = YES;
        self.downView.hidden = YES;
        self.webViewBottom.constant = 10;
    }
}

// 在子线程中定义定时器

- (void)bannerStart{
    _runTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimeLabel) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_runTimer forMode:NSDefaultRunLoopMode];
    
    [[NSRunLoop currentRunLoop] run];
}
//用于网络pdf文件
 - (CGPDFDocumentRef)pdfRefByDataByUrl:(NSURL *)aFileUrl {
         NSData *pdfData = [NSData dataWithContentsOfURL:aFileUrl];
     if (pdfData.length >0) {
         CFDataRef dataRef = (__bridge_retained CFDataRef)(pdfData);
         CGDataProviderRef proRef = CGDataProviderCreateWithCFData(dataRef);
         CGPDFDocumentRef pdfRef = CGPDFDocumentCreateWithProvider(proRef);
         
         CGDataProviderRelease(proRef);
         CFRelease(dataRef);
         
         return pdfRef;
     }
     return nil;
}


- (void)updateTimeLabel{
    if (readerTime == 1) {
        if (self.runTimer!=nil) {
            [self.runTimer invalidate];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //回调或者说是通知主线程刷新，
            self.iAgreeButton.enabled = YES;
            self.timeLa.backgroundColor = MAIN_COLOR_Red;
            _timeLa.text = @"我已阅读，确认无误并同意签字";
        });
        
        return;
    }
//    NSLog(@"readerTime---%d",readerTime);
    NSString *ttt = [NSString stringWithFormat:@"我已阅读，确认无误并同意签字（%ds）",readerTime];
        //通知主线程刷新
    dispatch_async(dispatch_get_main_queue(), ^{
        //回调或者说是通知主线程刷新，
        _timeLa.text = ttt;
    });
    readerTime--;
}

- (void)goPageAtIndex: (int)pagenum {
    [_mWebView.scrollView setContentOffset:CGPointMake(0, totalHeight/totalPage*(pagenum-1)) animated:NO];
//    [_wkWebView.scrollView setContentOffset:CGPointMake(0, totalHeight/totalPage*(pagenum-1)) animated:NO];
}

- (IBAction)okPress{
    _iAgreeButton.enabled = NO;
    [HandleNetProduct updateSigningStatusforBookingID:bookingId SignName:stepName Success:^(NSDictionary *data) {
//        _downView.hidden = YES;
        _iAgreeButton.enabled = YES;
        if (self.returnChangeOK) {
            self.returnChangeOK();
        }
        [self.navigationController popViewControllerAnimated:YES];
    } Failure:^(NSString *errorInfo) {
        _iAgreeButton.enabled = YES;
    }];
}

- (IBAction)hasRead:(id)sender {
    NSLog(@"已阅读---");
    if ([_timeLa.text isEqualToString:@"@下载至邮箱"]) {
        VerifySMSController *vc = (VerifySMSController *)[CKPuslichTool getViewControllerFromStroyBoard:@"My" viewID:@"VerifySMSController"];
        [vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        [vc setModalPresentationStyle:UIModalPresentationOverFullScreen];
        vc.returnVerifyOK = ^{
//            [self okPress];
        };
        vc.isEmail = YES;
        vc.emailSt = personlEmail;
        vc.bookingId = bookingId;
        
        [self presentViewController:vc animated:YES completion:nil];
    }else{
        if ([_stepDic[@"IsSMS"] isEqualToString:@"Yes"]) {
            //判断改为如果是最后一步 电子签约加密
            VerifySMSController *vc = (VerifySMSController *)[CKPuslichTool getViewControllerFromStroyBoard:@"My" viewID:@"VerifySMSController"];
            [vc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
            [vc setModalPresentationStyle:UIModalPresentationOverFullScreen];
            vc.returnVerifyOK = ^{
                [self okPress];
            };
            vc.emailSt = personlEmail;
            vc.isEmail = NO;
            
            [self presentViewController:vc animated:YES completion:nil];
        }else{
            [self okPress];
        }
    }
    
    
    
}

//必须实现 否则无法触发点击事件

//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
//     return YES;
//}

//- (void)webView:(WKWebView*)webView decidePolicyForNavigationResponse:(WKNavigationResponse*)navigationResponse decisionHandler:(void(^)(WKNavigationResponsePolicy))decisionHandler {
//
//    decisionHandler(WKNavigationResponsePolicyAllow);
//
//    NSLog(@"%s", __FUNCTION__);
//
//}
//
////开始加载
//- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
//    NSLog(@"开始加载网页");
//}
//
////加载完成
//- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    NSLog(@"加载完成");
//    [_wkWebView.scrollView setOpaque:NO];
//    _wkWebView.scrollView.backgroundColor = [UIColor whiteColor];
//    _wkWebView.scrollView.delegate = self;
//    [_wkWebView setOpaque:NO];
//
//    _wkWebView.backgroundColor = [UIColor colorWithHexString:@"#f4f4f4"];
//
//
//    //加载完成后隐藏progressView
//    [SVProgressHUD dismiss];
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//    totalHeight = webView.scrollView.contentSize.height;
//    [self loadMyTimer];
//}
//
////加载失败
//- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
//    NSLog(@"加载失败");
//    self.webTopHeight.constant = 0;
//    self.topView.hidden = YES;
//    self.downView.hidden = YES;
//    self.webViewBottom.constant = 10;
//
//    [SVProgressHUD dismiss];
//    //加载失败同样需要隐藏progressView
//}


#pragma mark - UIWebViewDelegate
//
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationTyp{


    return YES;

}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{

    self.mWebView.hidden = NO;
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    totalHeight = webView.scrollView.contentSize.height;
    [self loadMyTimer];
    
    //假的环形进度相关处理
//    _circleView.progress = 1;
//     sleep(2);
//    self.circleView.hidden = YES;

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    self.webTopHeight.constant = 0;
    self.topView.hidden = YES;
    self.downView.hidden = YES;
    self.webViewBottom.constant = 10;
    self.mWebView.hidden = NO;
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

}



#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    NSLog(@"scrollViewDidEndDecelerating");
    
    //    [[NSUserDefaults standardUserDefaults] setFloat:offsetY forKey:@"jingjinzhuimengren"];
    //
    //    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView; {
    if ([self.title isEqualToString:@"基金合同"]) {
        totalHeight = _mWebView.scrollView.contentSize.height;
        float pageH = totalHeight/totalPage;
        CGFloat offsetY =  _mWebView.scrollView.contentOffset.y;
        int index = offsetY/pageH+2;
        if (index < [_topHeaders[0] intValue]+1) {
            currentPage = 0;
            [_mCollection reloadData];
            return;
        }
        
        for (int i=0; i<_topHeaders.count; i++) {
            if (index ==[_topHeaders[i] intValue]+1) {
                currentPage = [_topHeaders[i] intValue]+1;
                break;
            }
        }
        [_mCollection reloadData];
    }
    
}


#pragma mark ---- UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _topHeaders.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TopFileHeaderCell *cell;
    if (indexPath.row == 0) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TopFileFirstCell" forIndexPath:indexPath];
    }else if (indexPath.row == _topHeaders.count - 1){
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TopFileLastCell" forIndexPath:indexPath];
    }else{
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TopFileMiddleCell" forIndexPath:indexPath];
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.nameLa.text = _topTitles[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    if ([_topHeaders[indexPath.row] intValue]>currentPage){
        cell.leftLa.backgroundColor = [UIColor colorWithHexString:@"dfdfdf"];
        cell.rightLa.backgroundColor = [UIColor colorWithHexString:@"dfdfdf"];
        cell.redImage.image = [UIImage imageNamed:@"gray"];
    }else{
        cell.leftLa.backgroundColor = MAIN_COLOR_Red;
        cell.rightLa.backgroundColor = MAIN_COLOR_Red;
        cell.redImage.image = [UIImage imageNamed:@"red"];
    }
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    float topWidth = Main_Screen_Width;//底部的高度
    return (CGSize){(topWidth)/_topHeaders.count,54};
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.0f;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0.0f;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    currentPage = [_topHeaders[indexPath.row] intValue]+1;
    [self goPageAtIndex:currentPage];
    [_mCollection reloadData];
}
@end
